package com.mwumz.third.common;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.common.collect.Maps;
import io.swagger.annotations.ApiModelProperty;

import java.util.List;
import java.util.Map;

/**
 * @Author: wumz
 * @Date: 2020/7/2 15:07
 * @Version 1.0
 */
public class PageResult<T> {
    private Long pageIndex;
    private Long totalCount;
    private Long pageSize;
    private List<T> pageData;
    @ApiModelProperty(
            hidden = true
    )
    @JsonIgnore
    private Map<String, Object> _extra = Maps.newHashMap();

    public PageResult() {
    }

    public static <T> PageResult<T> of(List<T> pageData, Page page) {
        PageResult<T> pageResult = new PageResult();
        pageResult.pageData = pageData;
        pageResult.pageIndex = page.getPageIndex();
        pageResult.pageSize = page.getPageSize();
        pageResult.totalCount = page.getTotalCount();
        return pageResult;
    }

    public static <T> PageResult<T> of(PageList<T> pageData) {
        PageResult<T> pageResult = new PageResult();
        pageResult.pageData = pageData;
        pageResult.pageIndex = pageData.getPageNum();
        pageResult.pageSize = pageData.getPageSize();
        pageResult.totalCount = pageData.getTotalCount();
        return pageResult;
    }

    public Response toResponse() {
        return Response.success(this);
    }

    public List<T> getPageData() {
        return this.pageData;
    }

    public PageResult<T> setPageData(List<T> pageData) {
        this.pageData = pageData;
        return this;
    }

    public long getTotalCount() {
        return this.totalCount;
    }

    public PageResult<T> setTotalCount(long totalCount) {
        this.totalCount = totalCount;
        return this;
    }

    public long getPageSize() {
        return this.pageSize;
    }

    public PageResult<T> setPageSize(long pageSize) {
        this.pageSize = pageSize;
        return this;
    }

    public long getPageIndex() {
        return this.pageIndex;
    }

    public PageResult<T> setPageIndex(long pageIndex) {
        this.pageIndex = pageIndex;
        return this;
    }

    @JsonIgnore
    public Map<String, Object> getExtra() {
        return this._extra;
    }

    public PageResult<T> putExtra(String key, Object value) {
        this._extra.put(key, value);
        return this;
    }

    public long getTotalPage() {
        if (this.getPageSize() == 0L) {
            return 0L;
        } else {
            long pages = this.getTotalCount() / this.getPageSize();
            if (this.getTotalCount() % this.getPageSize() != 0L) {
                ++pages;
            }

            return pages;
        }
    }
}
